#include "UserOperations.h"




// 用户类构造函数实现
User::User(string   u,  string   p) : username(u), password(p) {}

// 实际用户操作类方法实现
bool UserOperations::registerUser( User   user) {
    ofstream ofs("./user.txt", ios::app);
    if (!ofs) {
       // cerr << "无法打开文件进行写入。" << endl;
        return false;
    }
    ofs << user.username << " " << user.password << endl;
    ofs.close();
    return true;
}


bool UserOperations::readTxt(){
     ifstream ifs("./user.txt");
    if (!ifs) {
        return false;
    }
    std::string u, p;
    while (ifs >> u >> p) {
        User user(u ,p);
        users.push_back(user);
    }
    ifs.close();
    return true;  // 登录失败
}


bool UserOperations::ifUser(string userName){
int i;
for(i=0;i<users.size();i++){
    if(users[i].username==userName)
    return true;
}
return false;
}





bool UserOperations::loginUser( string   username,  string   password) {
     int i;
     for(i=0;i<users.size();i++){
        User u=users[i];
        if(u.username==username &&u.password==password)
        return true;
     }
    return false;  // 登录失败
}


// 代理类方法实现
UserOperationsProxy::UserOperationsProxy() {
    userOps.readTxt();
}


bool UserOperationsProxy::registerUser( User   user) {
  //  cout << "注册操作开始..." << endl;
    bool success = userOps.registerUser(user);
    if(success)
    {
        userOps.readTxt(); // 确保注册后用户列表更新
    }
    return success;
}



bool UserOperationsProxy::ifUser(string userName){
   if(userOps.ifUser(userName)){
    return true;
   }
   return false;
}



bool UserOperationsProxy::loginUser( string   username,  string   password) {
   // cout << "登录操作开始..." << endl;
    bool success = userOps.loginUser(username, password);
    if (success) {
        currentUser=new User(username,password);
       // cout << "登录成功。" << endl;
    } else {
       // cout << "用户名或密码错误。" << endl;
    }
    return success;
}
